<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;

class ExpressUser extends Model
{
    public $autoWriteTimestamp = "init";

    public $createTime = "createtime";

    public $updateTime = "updatetime";

    public static  function setMoney($uid,$express_id,$money,$remark,$extend=[],$type="with",$order_id=0)
    {
        Db::startTrans();
        try {
            $info = self::where("id",$express_id)->lock(true)->find();
            if(($info['money']+$money) < $info["money"]){
                throw new Exception("余额不足");
            }
            $before = $info["money"];
            $after  = $info["money"] + $money;
            $upd_data = [
                "money" => $after,
            ];
            $upd_data = array_merge($upd_data,$extend);
            $r = self::where("id",$express_id)->update($upd_data);
            if(!$r){
                throw new Exception("更新快递员信息失败");
            }
            ExpressAssetslog::create([
                "user_id"   => $uid,
                "express_id"=> $express_id,
                "money"     => $money,
                "before"    => $before,
                "after"     => $after,
                "memo"      => $remark,
                "type"      => $type,
                "order_id"  => $order_id
            ]);
            Db::commit();
            return true;
        }catch (Exception $e){
            Db::rollback();
            return $e->getMessage();
        }
    }
}